
/**
 * Created by admin on 2017/10/26.
 */
$(document).ready(function() {
    var VAL = {
        NORMAL : "0000000",
        EVT_USER     : $("#userId").text(),
        T_FBPBISMTR  : "FBPBISMTR",
        T_MIPWOBOM   : "MIPWOBOM",
        T_MWPMTROPE  : "MWPMTROPE",
        T_FBPBISDAT : "FBPBISDAT",
        DISABLED_ATTR : {
            'disabled' : true
        },
        ENABLED_ATTR : {
            'disabled' : false
        }
    };
    var domObj = {
        buttons : {
            $import_btn 	: $("#import_btn"),
            $download_btn  	: $("#download_btn"),
            $query_btn    	: $("#query_btn"),
            $save_btn    	: $("#save_btn"),
            $del_btn    	: $("#del_btn"),
            $select_btn    	: $("#select_btn"),
        },
        $mtrlprodId    : $("#mtrlprodId"),
        $WhIdSel    :$("#WhIdSel"),
        $FinishedSel :$("#FinishedSel"),
        grids : {
            $toolListDiv 	: $("#toolListDiv"),
            $toolListGrd 	: $("#toolListGrd"),
            $toolListPg 	: $("#toolListPg"),

            $whListDiv 	: $("#whListDiv"),
            $whListGrd 	: $("#whListGrd"),
            $whListPg 	: $("#whListPg")
        }
    };
    var iniGridInfo = function(){
        var toolListCM = [
            {name: 'mtrl_prod_id_fk',  index: 'mtrl_prod_id_fk',    label:"物料代码",    width: 230},
            {name: 'mtrl_lot_id',  index: 'mtrl_lot_id',       label:"物料批次",      width: 180},
            {name: 'mtrl_qty',      index: 'mtrl_qty',    label: "物料数量",  width: 180},

        ];
        domObj.grids.$toolListGrd.jqGrid({
            url: "",
            datatype: "local",
            mtype: "POST",
            height: 400,
            autowidth: true,
            shrinkToFit:false,
            autoScroll: false,
            resizable: true,
            loadonce: true,
            viewrecords: true,
            rownumbers: true,
            rowNum: 20,
            multiselect : true,
            emptyrecords: true,
            colModel: toolListCM,
            pager: "#toolListPg"
        });
        var whListCM = [
            {name: 'mtrl_prod_id_fk',  index: 'mtrl_prod_id_fk',       label:MTRL_ID_TAG,      width: 240},
            {name: 'mtrl_lot_id',  index: 'mtrl_lot_id',               label:MTRL_LOT_ID_TAG,      width: 240},
            {name: 'mtrl_name',        index: 'mtrl_name',             label:"物料名称",            width: 240},
            {name: 'mtrl_qty',         index: 'mtrl_qty',              label:"物料累计数量",             width: 200},
            {name: 'evt_qty',         index: 'evt_qty',                label:"物料累计使用数量",             width: 190},
            {name: 'mtrl_wh_qty',      index: 'mtrl_wh_qty',           label:"库存数量",          width: 180},
        ];
        domObj.grids.$whListGrd.jqGrid({
            url: "",
            datatype: "local",
            mtype: "POST",
            height: 400,
            autowidth: true,
            shrinkToFit:false,
            autoScroll: false,
            resizable: true,
            loadonce: true,
            viewrecords: true,
            rownumbers: true,
            rowNum: 20,
            emptyrecords: true,
            colModel: whListCM,
            pager: "#whListPg"
        });

    };
    var toolFunc = {
        iniMtrlSel :function(){
            var iary={
            }
            var inObj = {
                trx_id : VAL.T_FBPBISMTR,
                action_flg : "Q",
                iary : [iary]
            };
            var outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                var options = [];
                domObj.$mtrlprodId.append("<option ></option>");
                for(var i=0; i<outObj.oary.length; i++){
                    if(outObj.oary[i]["mtrl_cate"] != "BACK"){//除去备品备件类型的物料
                        options[i] = "<option value ="+ outObj.oary[i]["mtrl_prod_id"] +">"+outObj.oary[i]["mtrl_prod_id"]+":"+ outObj.oary[i]["mtrl_prod_dsc"] + "</option>";
                    }
                }
                domObj.$mtrlprodId.append(options.join(""));
                domObj.$mtrlprodId.select2({
                    theme : "bootstrap"
                });
            }
        },
        iniWHIdSel :function(){
            var inObj = {
                trx_id : VAL.T_FBPBISDAT,
                action_flg : "Q",
                iary : [{
                    data_cate: 'DEST',
                    data_item  : 'L'
                }]
            };
            var outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                SelectDom.addSelectArr(domObj.$WhIdSel, outObj.oary, "data_ext","data_desc","",true);
            }
        },
        iniFinishedSel :function(){
            var inObj = {
                trx_id : VAL.T_FBPBISDAT,
                action_flg : "Q",
                iary : [{
                    data_cate: 'DEST',
                    data_item  : 'P'
                }]
            };
            var outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                SelectDom.addSelectArr(domObj.$FinishedSel, outObj.oary, "data_ext","data_desc","",true);
            }
        }
    };
    var btnFunc = {
        queryFunc  :function(){
            var mtrlProdIdFk = $.trim(domObj.$mtrlprodId.val());
            var WhIdSel=$.trim(domObj.$WhIdSel.val());
            /*if (!mtrlProdIdFk) {
                showErrorDialog("","请选择物料代码！");
                return;
            }*/
            if(!WhIdSel){
                showErrorDialog("", "请选择仓库代码");
                return false;
            }
            var iary={
                mtrl_prod_id_fk : mtrlProdIdFk,
               dest_shop : WhIdSel
            }
            var inObj = {
                trx_id : VAL.T_MWPMTROPE,
                action_flg : "Q",
                iary : [iary]
            };
            var outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                setGridInfo(outObj.oary, domObj.grids.$whListGrd);
            }
        },
        selectFileFunc  :function(){
            domObj.buttons.$select_btn.click();
        },
        uploadFnc  : function (obj) {
            //清空jqgrid里面的数据
            domObj.grids.$toolListGrd.jqGrid("clearGridData")
            var crr_query="N";
            /*
             FileReader共有4种读取方法：
             1.readAsArrayBuffer(file)：将文件读取为ArrayBuffer。
             2.readAsBinaryString(file)：将文件读取为二进制字符串
             3.readAsDataURL(file)：将文件读取为Data URL
             4.readAsText(file, [encoding])：将文件读取为文本，encoding缺省值为'UTF-8'
             */
            var wb;//读取完成的数据
            var rABS = true; //是否将文件读取为二进制字符串
            if(!obj.files) {
                return;
            }
            var fileName = obj.value;
            if(fileName.length > 1 && fileName ) {
                var ldot = fileName.lastIndexOf(".");
                var type = fileName.substring(ldot + 1);
                if(!(type=="xlsx"||type=="xls")) {
                    showErrorDialog("", "只能导入excel文件");
                    return;
                }
            }
            var f = obj.files[0];
            var reader = new FileReader();
            reader.onload = function(e) {
                var data = e.target.result;
                if(rABS) {
                    wb = XLSX.read(btoa(fixdata(data)), {//手动转化
                        type: 'base64'
                    });
                } else {
                    wb = XLSX.read(data, {
                        type: 'binary'
                    });
                }
                //wb.SheetNames[0]是获取Sheets中第一个Sheet的名字
                //wb.Sheets[Sheet名]获取第一个Sheet的数据
                var data = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
                setGridInfo(data, domObj.grids.$toolListGrd);
            };
            if(rABS) {
                reader.readAsArrayBuffer(f);
            } else {
                reader.readAsBinaryString(f);
            }
            function fixdata(data) { //文件流转BinaryString
                var o = "", l = 0, w = 10240;
                for(; l < data.byteLength / w; ++l) o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)));
                o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)));
                return o;
            }
        },
        downloadTempFun: function () {
            if ($("#downForm").length > 0) {
                $("#downForm").remove();
            }
            var str = '<form id="downForm" action="download.do" method="post">';
            str = str + '<input type="hidden" name="fileName" id= "fileName" />';
            str = str + "</form>";
            $(str).appendTo("body");
            $("#fileName").val("4100.xlsx");
            $("#downForm").submit();
        },
        saveFun: function () {
            var WhIdSel=$.trim(domObj.$WhIdSel.val());
            if(!WhIdSel){
                showErrorDialog("", "请选择仓库代码");
                return false;
            }
            var ids = domObj.grids.$toolListGrd.jqGrid('getGridParam','selarrrow');
            if(ids.length<1){
                showErrorDialog("", "导入信息列表中至少选择一条数据进行保存");
                return false;
            }
            var iary =[];
            for(var i=0;i<ids.length;i++) {
                var rowData = domObj.grids.$toolListGrd.jqGrid("getRowData", ids[i]);
                if(!rowData.mtrl_qty){
                    showErrorDialog("", "第"+ $('#' + ids[i])[0].rowIndex + "行库存数量不能为空！");
                    return false;
                }
                if(!ComRegex.isNumber(rowData.mtrl_qty)){
                    showErrorDialog("", "第"+ $('#' + ids[i])[0].rowIndex + "行库存数值格式不正确！");
                    return false;
                }
                var iaryA={
                    mtrl_prod_id_fk : rowData.mtrl_prod_id_fk,
                    mtrl_lot_id     : rowData.mtrl_lot_id,
                    mtrl_qty        : rowData.mtrl_qty,
                    dest_shop :   WhIdSel
                }
                iary.push(iaryA);
            }
            var inObj = {
                trx_id : VAL.T_MWPMTROPE,
                action_flg : "S",
                evt_usr :VAL.EVT_USER,
                iary : iary
            };
            var outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                showSuccessDialog("成功导入库存信息");
                var length = ids.length;
                for(var i=0;i<length;i++){
                    domObj.grids.$toolListGrd.jqGrid("delRowData",ids[0]);
                }
                btnFunc.queryFunc();
            }
        },
        delFun: function () {
           var WhIdSel=$.trim(domObj.$WhIdSel.val());
            if(!WhIdSel){
                showErrorDialog("", "请选择线边仓库代码");
                return false;
            }
            var  finishShop = $.trim(domObj.$FinishedSel.val());
            if(!finishShop){
                showErrorDialog("", "请选择成品仓库代码");
                return false;
            }
            var ids = domObj.grids.$toolListGrd.jqGrid('getGridParam','selarrrow');
            if(ids.length<1){
                showErrorDialog("", "导入信息列表中至少选择一条数据进行删除");
                return false;
            }
            $("#del_btn").showCallBackWarnningDialog({
                errMsg  : "是否删除库存信息,请确认!!!!",
                callbackFn : function(data) {
                    if(data.result==true){
                        var iary =[];
                        for(var i=0;i<ids.length;i++) {
                            var rowData = domObj.grids.$toolListGrd.jqGrid("getRowData", ids[i]);
                            if(!rowData.mtrl_qty){
                                showErrorDialog("", "第"+ $('#' + ids[i])[0].rowIndex + "行库存数量不能为空！");
                                return false;
                            }
                            if(!ComRegex.isNumber(rowData.mtrl_qty)){
                                showErrorDialog("", "第"+ $('#' + ids[i])[0].rowIndex + "行库存数值格式不正确！");
                                return false;
                            }
                            var iaryA={
                                mtrl_prod_id_fk : rowData.mtrl_prod_id_fk,
                                mtrl_lot_id     : rowData.mtrl_lot_id,
                                mtrl_qty        : rowData.mtrl_qty,
                                dest_shop       :   WhIdSel,
                                finish_shop     :   finishShop

                            }
                            iary.push(iaryA);
                        }
                        var inObj = {
                            trx_id : VAL.T_MWPMTROPE,
                            action_flg : "D",
                            evt_usr :VAL.EVT_USER,
                            iary : iary
                        };
                        var outObj = comTrxSubSendPostJson(inObj);
                        if (outObj.rtn_code == VAL.NORMAL) {
                            var length = ids.length;
                            for(var i=0;i<length;i++){
                                domObj.grids.$toolListGrd.jqGrid("delRowData",ids[0]);
                            }
                            showSuccessDialog("删除成功");
                            btnFunc.queryFunc();
                        }
                    }
                }
            });

        }
    };
    /**
     * Ini contorl's data
     */
    var iniContorlData = function(){
        toolFunc.iniMtrlSel();
        toolFunc.iniWHIdSel();
        toolFunc.iniFinishedSel();
    };

    /**
     * Bind button click action
     */
    var iniButtonAction = function(){
        domObj.buttons.$import_btn.click(function(){
            btnFunc.selectFileFunc();
        });
        domObj.buttons.$download_btn.click(function(){
            btnFunc.downloadTempFun();
        });
        domObj.buttons.$query_btn.click(function(){
            btnFunc.queryFunc();
        });
        domObj.buttons.$save_btn.click(function(){
            btnFunc.saveFun();
        });
        domObj.buttons.$del_btn.click(function(){
            btnFunc.delFun();
        });
        domObj.buttons.$select_btn.change(function() {
            btnFunc.uploadFnc(this);
        });
    };

    /**
     * Other action bind
     */
    var otherActionBind = function(){
        $("form").submit(function(){
            return false;
        });
    };
    /**
     * Ini view, data and action bind
     */
    var initializationFunc = function(){
        iniGridInfo();
        iniContorlData();
        iniButtonAction();
        otherActionBind();
    };

    initializationFunc();
    //表格自适应
    function resizeFnc(){
        var offsetBottom, divWidth,offsetBottom1, divWidth1;
        divWidth = $("#toolListDiv").width();
        offsetBottom =  $(window).height() - $("#toolListDiv").offset().top;
        $("#toolListDiv").height(offsetBottom * 0.95);
        $("#toolListGrd").setGridWidth(divWidth * 0.85);
        $("#toolListGrd").setGridHeight(offsetBottom * 0.99 - 51);
        //2
        divWidth1= $("#whListDiv").width();
        offsetBottom1 =  $(window).height() - $("#whListDiv").offset().top;
        $("#whListDiv").height(offsetBottom1 * 0.95);
        $("#whListGrd").setGridWidth(divWidth1 * 0.85);
        $("#whListGrd").setGridHeight(offsetBottom1 * 0.99 - 51);

    };
    resizeFnc();
    $(window).resize(function() {
        resizeFnc();
    });
});
